import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'
import i18n from '@/i18n'

export interface User {
  id: number
  username: string
  email: string
  role: string
  status: 'active' | 'inactive'
  created_at: string // ISO string format
  updated_at: string // ISO string format
  roles: Array<{
    id: number
    name: string
    code: string
    description?: string
  }>
  full_name?: string
  bio?: string
}

export interface LoginForm {
  username: string
  password: string
  captcha_id: string
  captcha_text: string
}

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(localStorage.getItem('token'))
  const user = ref<User | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)
  const userPermissions = ref<string[]>([])

  const isAuthenticated = computed(() => !!token.value)
  const userRole = computed(() => 'user') // Backend does not provide role, defaulting to 'user'
  const userRoles = computed(() => user.value?.roles || [])

  // 设置 axios 默认请求头
  if (token.value) {
    axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
  }

  async function login(loginForm: LoginForm) {
    loading.value = true
    error.value = null
    
    try {
      // Call the backend login API
      console.log('Attempting login to /api/users/login with:', loginForm);
      const loginResponse = await axios.post('/api/users/login', loginForm)
      console.log('Login response:', loginResponse);
      
      const accessToken = loginResponse.data.access_token
      token.value = accessToken
      
      // Set axios default headers for the subsequent request
      axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`
      
      // Fetch user information using the new token
      console.log('Attempting to fetch user info from /api/users/me');
      const userResponse = await axios.get('/api/users/me')
      console.log('User info response:', userResponse);
      user.value = userResponse.data
      
      // Save to localStorage
      localStorage.setItem('token', accessToken)
      localStorage.setItem('user', JSON.stringify(user.value))
      
      return { success: true }
    } catch (err: any) {
      console.error('Login error:', err)
      if (err.response) {
        // Backend returned an error
        error.value = err.response.data.detail || i18n.global.t('login.loginFailed')
      } else if (err.request) {
        // Request made but no response received
        error.value = i18n.global.t('login.networkError')
      } else {
        // Something else happened
        error.value = i18n.global.t('login.loginFailed')
      }
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  function logout() {
    token.value = null
    user.value = null
    error.value = null
    
    // 清除 localStorage
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    
    // 清除 axios 请求头
    delete axios.defaults.headers.common['Authorization']
  }

  // 初始化用户信息
  function initUser() {
    const savedToken = localStorage.getItem('token')
    const savedUser = localStorage.getItem('user')
    
    if (savedToken && savedUser) {
      token.value = savedToken
      user.value = JSON.parse(savedUser)
      axios.defaults.headers.common['Authorization'] = `Bearer ${savedToken}`
      // 加载用户权限
      loadUserPermissions()
    }
  }

  // 加载用户权限
  async function loadUserPermissions() {
    if (!user.value) return
    
    try {
      const response = await axios.get('/api/users/me')
      const userData = response.data
      
      // 从用户角色中提取权限
      const permissions: string[] = []
      
      // 根据角色代码分配权限
      userData.roles?.forEach((role: any) => {
        switch (role.code) {
          case 'super_admin':
            permissions.push(
              'user:read', 'user:create', 'user:update', 'user:delete',
              'role:read', 'role:create', 'role:update', 'role:delete',
              'permission:read', 'permission:create', 'permission:update', 'permission:delete',
              'widget:read', 'widget:create', 'widget:update', 'widget:delete',
              'system:manage'
            )
            break
          case 'system_admin':
            permissions.push(
              'user:read', 'user:create', 'user:update', 'user:delete',
              'role:read', 'role:create', 'role:update', 'role:delete',
              'permission:read', 'permission:create', 'permission:update', 'permission:delete',
              'system:manage'
            )
            break
          case 'user_admin':
            permissions.push(
              'user:read', 'user:create', 'user:update', 'user:delete',
              'role:read', 'role:create', 'role:update', 'role:delete'
            )
            break
          case 'widget_admin':
            permissions.push(
              'widget:read', 'widget:create', 'widget:update', 'widget:delete'
            )
            break
          case 'normal_user':
            permissions.push(
              'user:read', 'role:read', 'permission:read', 'widget:read'
            )
            break
        }
      })
      
      userPermissions.value = [...new Set(permissions)] // 去重
    } catch (error) {
      console.error('Failed to load user permissions:', error)
      userPermissions.value = []
    }
  }

  // 检查用户是否有指定权限
  function hasPermission(permission: string): boolean {
    return userPermissions.value.includes(permission)
  }

  // 检查用户是否有任意一个权限
  function hasAnyPermission(permissions: string[]): boolean {
    return permissions.some(permission => hasPermission(permission))
  }

  // 检查用户是否有所有权限
  function hasAllPermissions(permissions: string[]): boolean {
    return permissions.every(permission => hasPermission(permission))
  }

  // 检查用户是否有指定角色
  function hasRole(roleCode: string): boolean {
    return userRoles.value.some(role => role.code === roleCode)
  }

  // 检查用户是否有任意一个角色
  function hasAnyRole(roleCodes: string[]): boolean {
    return roleCodes.some(roleCode => hasRole(roleCode))
  }

  return {
    token,
    user,
    loading,
    error,
    userPermissions,
    isAuthenticated,
    userRole,
    userRoles,
    login,
    logout,
    initUser,
    loadUserPermissions,
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    hasRole,
    hasAnyRole
  }
})
